package com.alm.handle.service.impl;


import com.alm.common.constant.UserConstants;
import com.alm.common.core.redis.RedisCache;
import com.alm.common.utils.StringUtils;
import com.alm.handle.core.domain.entity.AlmAutoEneraHis;
import com.alm.handle.core.domain.entity.SysAreaInfo;
import com.alm.handle.core.domain.entity.SysDevCurrentData;
import com.alm.handle.core.domain.entity.SysDevInfo;
import com.alm.handle.core.domain.entity.rs.StatisticsStatementRS;
import com.alm.handle.core.domain.entity.rs.StatisticsStatementSumRS;
import com.alm.handle.core.domain.entity.vo.CurrentVo;
import com.alm.handle.mapper.AlmAutoEneraHisMapper;
import com.alm.handle.mapper.SysAreaInfoMapper;
import com.alm.handle.mapper.SysDevCurrentDataMapper;
import com.alm.handle.mapper.SysDevInfoMapper;
import com.alm.handle.service.ISysAreaInfoService;
import com.alm.handle.util.ELeCurrentUtil;
import com.alm.handle.util.SoketEleKey;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysAreaInfoServiceImpl implements ISysAreaInfoService {

    @Resource
    private SysAreaInfoMapper areaInfoMapper;
    @Autowired
    private SysDevCurrentDataMapper sysDevCurrentDataMapper;
    @Resource
    private AlmAutoEneraHisMapper hisMapper;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private SysDevInfoMapper devInfoMapper;
    @Override
    public List<SysAreaInfo> selectAreaList(Long commpanyId) {
        QueryWrapper<SysAreaInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_by", commpanyId);
        return areaInfoMapper.selectList(queryWrapper);
    }

    @Override
    public SysAreaInfo selectAreaInfoById(Long menuId) {
        return areaInfoMapper.selectById(menuId);
    }

    @Override
    public boolean hasChildByAreaId(Long menuId) {
        QueryWrapper<SysAreaInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", menuId);
        Integer i = areaInfoMapper.selectCount(queryWrapper);
        return i != null && i > 0;
    }

    @Override
    public int deleteAreaById(Long menuId) {
        return areaInfoMapper.deleteById(menuId);
    }

    @Override
    public boolean checkMenuNameUnique(SysAreaInfo area) {
        Long menuId = StringUtils.isNull(area.getMenuId()) ? -1L : area.getMenuId();
        QueryWrapper<SysAreaInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_name", area.getMenuName());
        queryWrapper.eq("parent_id", area.getParentId());
        SysAreaInfo sysAreaInfo = areaInfoMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(sysAreaInfo) && !area.getMenuId().equals(sysAreaInfo.getMenuId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertArea(SysAreaInfo area) {
        return areaInfoMapper.insert(area);
    }

    @Override
    public int updateArea(SysAreaInfo area) {
        return areaInfoMapper.updateById(area);
    }


    @Override
    public List<StatisticsStatementRS> getStatisData(Integer areaid,Long startTime,Long endTime){

        // o_o ....该方法会使数据库负载极高，因为for循环查询数据库，频繁建立断开连接

        SysAreaInfo areaInfo=  areaInfoMapper.selectById(areaid);
        List<StatisticsStatementRS> rsList=null;
        if(areaInfo!=null){
            findAllChild(areaInfo);
            areaInfo.setChildIds(areaid.toString());
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.select("device_id");
            queryWrapper.in("region_id",areaInfo.getChildIds().split(","));
//            queryWrapper.apply("region_id in ( {0} )",areaInfo.getChildIds());
            List<SysDevInfo> list=devInfoMapper.selectList(queryWrapper);
            if(list!=null&&list.size()>0){
                List<String> devmacs=list.stream().map(SysDevInfo::getDeviceId).collect(Collectors.toList());
                queryWrapper=new QueryWrapper();
                queryWrapper.ge("add_time",startTime);
                queryWrapper.le("add_time",endTime);
                queryWrapper.in("device_id",devmacs);
                queryWrapper.groupBy("info_no");
                queryWrapper.select("info_no");
                // 获取统计的横向维度，即 时间 yyyy-MM-dd hh时
                List<AlmAutoEneraHis> his=hisMapper.selectList(queryWrapper);
                if(his!=null&&his.size()>0){
                    rsList=new ArrayList<>();
                    for(AlmAutoEneraHis eneraHis:his){
                        StatisticsStatementRS rs=new StatisticsStatementRS();
                        queryWrapper=new QueryWrapper();
                        queryWrapper.eq("info_no",eneraHis.getInfoNo());
                        queryWrapper.in("device_id",devmacs);
                        // 根据设备mac和时间维度查询数据
                        List<AlmAutoEneraHis> data=hisMapper.selectList(queryWrapper);
                        // 总能耗
                        BigDecimal sumele=new BigDecimal(0);
                        // 总能耗
                        BigDecimal sumpower=new BigDecimal(0);
                        // 工作设备数
                        Integer workDev = 0;
                        // 在线设备数
                        Integer onlineDev = 0;
                        // 异常设备数
                        Integer exDev=0;
                        // 遍历列表，统计总能耗，总能耗，工作设备数，在线设备数，异常设备数
                        for (AlmAutoEneraHis eneraHis1:data){
                            sumpower= sumpower.add( eneraHis1.getActivePower());
                            sumele= sumele.add( eneraHis1.getElectricCurrent());
                            if(eneraHis1.getWorkStatus()!=null&&eneraHis1.getWorkStatus()==1) {
                                workDev += 1;
                            }
                            if(eneraHis1.getExStatus()!=null&&eneraHis1.getExStatus()==1){
                                exDev+=1;
                            }
                            if(eneraHis1.getOnlineStatus()!=null&&eneraHis1.getOnlineStatus()==1){
                                onlineDev+=1;
                            }
                        }
                        rs.setSumDev(workDev);
                        rs.setSumOnlineDev(onlineDev);
                        rs.setSumexDev(exDev);
                        rs.setSumPower(sumpower.setScale(4,BigDecimal.ROUND_DOWN));
                        rs.setSumEnerty(sumele.setScale(4,BigDecimal.ROUND_DOWN));
                        rs.setData(eneraHis.getInfoNo());
                        rsList.add(rs);
                    }
                }
            }
        }
        return rsList;
    }



    @Override
    public void findAllChild(SysAreaInfo sysAreaInfo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id", sysAreaInfo.getMenuId());
        List<SysAreaInfo> resources = areaInfoMapper.selectList(wrapper);
        if(resources!=null&&resources.size()>0){
            String result = resources.stream()
                    .map(SysAreaInfo::getMenuId)
                    .map(String::valueOf) // 将整数转换为字符串
                    .collect(Collectors.joining(",")); // 使用逗号拼接
            sysAreaInfo.setChildIds(result);
        }
        if (resources != null && resources.size() > 0) {
            for (SysAreaInfo areaInfo:resources){
                findAllChild(areaInfo);
                sysAreaInfo.setChildIds(areaInfo.getChildIds()); ;
            }
        }
    }
}
